package com.example.automatic.receiver;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;

public class SMSContentObserver extends ContentObserver {

    private Context mContext;
    private SmsListener mSmsListener;

    public SMSContentObserver(Handler handler, Context mContext, SmsListener mSmsListener) {
        super(handler);
        this.mContext = mContext;
        this.mSmsListener = mSmsListener;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        Uri inboxUri = Uri.parse("content://sms/inbox");
        @SuppressLint("Recycle")
        Cursor cursor = mContext.getContentResolver().query(inboxUri, null, null, null, "date desc");
        if (cursor == null) {
            return;
        }
        if (!cursor.moveToFirst()) {
            return;
        }
        //接收短信的号码
        String smsMobile = cursor.getString(cursor.getColumnIndex("address"));
        //短信内容
        String smsContent = cursor.getString(cursor.getColumnIndex("body"));

        if (mSmsListener != null) {
            mSmsListener.onResult(smsMobile, smsContent);
        }
    }

    /**
     * 短信回调接口
     */
    public interface SmsListener {
        void onResult(String phone, String content);
    }
}
